package com.ffyc.cms.controller;

import com.ffyc.cms.common.CommonResult;
import com.ffyc.cms.model.Admin;
import com.ffyc.cms.service.AdminService;
import com.ffyc.cms.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping(path = "/admin")
public class AdminController {

    @Autowired
    AdminService adminService;

    /*
    上传头像
     */
    @PostMapping(path = "/fileUpload")
    public CommonResult fileUpload(@RequestParam("fileName") CommonsMultipartFile file, HttpSession session) {
        CommonResult commonResult = null;
        Admin admin = (Admin) session.getAttribute("admin");
        File f0 = new File("D:\\userImg\\" + admin.getAccount());
        if (!f0.exists()) {
            f0.mkdir();
        }
        String oldFileName = file.getOriginalFilename();
        String newFileName = StringUtil.newFileName(oldFileName);
        File f = new File(f0, newFileName);//输出路径
        try {
            file.transferTo(f);
            Admin a = new Admin();
            a.setId(admin.getId());
            a.setNewFileName(newFileName);
            a.setOldFileName(oldFileName);
            adminService.updateAdmin(a);
            commonResult = new CommonResult(200, "上传成功", a);
        } catch (IOException e) {
            e.printStackTrace();
            commonResult = new CommonResult(500, "上传失败", null);
        }
        return commonResult;
    }

    /*
    修改密码
     */
    @PostMapping(value = "/updatePwd")
    public CommonResult updateAdmin(Admin admin, HttpSession session) {
        CommonResult commonResult = null;
        /*
        拿到session中的当前登录账号信息
         */
        Admin admin1 = (Admin) session.getAttribute("admin");
        try {
            admin1.setPassword(admin.getPassword());
            adminService.upadtePwd(admin1);
            commonResult = new CommonResult(200, "修改成功", admin1);
        } catch (Exception e) {
            e.printStackTrace();
            commonResult = new CommonResult(500, "修改失败", null);
        }
        return commonResult;
    }
}
